package cn.jbit.reactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/8
 */
public class SubReactor implements Runnable{

    private  final Selector selector; //多路复用器

    private  boolean register=false;//注册开关表示，

    private  int num; //序号，也就是Acceptor初始化时SubReactor的下标

    SubReactor(Selector selector,int num) {
        this.selector = selector;
        this.num=num;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()){
            System.out.println(String.format("%d号SubReactor等待注册中...",num));
            while (!Thread.interrupted()&&!register){
                try {
                    if (selector.select()==0){
                        continue;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Set<SelectionKey> selectionKeys=selector.selectedKeys();
                Iterator  iterators=selectionKeys.iterator();
                while (iterators.hasNext()){
                        dispatch((SelectionKey) iterators.next());
                        iterators.remove();
                }
            }
        }
    }

    //分发请求
    private  void dispatch(SelectionKey selectionKey){
        Runnable runnable= (Runnable) selectionKey.attachment();//attachment代表进行处理事件
        if (runnable!=null){
            runnable.run();
        }
    }

    void registering(boolean register){
        this.register=register;
    }
}
